import base64

import cv2
import numpy as np
from fastapi import FastAPI, File, Form, UploadFile
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
import erniebot
from PIL import Image
import io
from aip import AipImageClassify

app = FastAPI()
origins = [
    "http://localhost.tiangolo.com",
    "https://localhost.tiangolo.com",
    "http://localhost",
    # "http://localhost:63343",
    "http://localhost:63342",
]
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


class PoeSimpleReq(BaseModel):
    access_token: str
    app_id: str
    api_key: str
    classify_secret_key: str
    file: bytes = File(default=None)


#
# @app.post("/poe")
# async def read_root(access_token: str = Form(), app_id: str = Form(), api_key: str = Form(),
#                     classify_secret_key: str = Form(), image: UploadFile = File()):
#     print(access_token)
#     print(app_id)
#     print(api_key)
#     print(classify_secret_key)
#     # print(image.file.read())
#     # print(image.size)
#     return {"1": "1"}


@app.post("/poe")
async def read_root(access_token: str = Form(), app_id: str = Form(), api_key: str = Form(),
                    classify_secret_key: str = Form(), image: UploadFile = File()):
    if access_token is None or app_id is None or api_key is None or classify_secret_key is None or classify_secret_key is None or image is None:
        return "Supplementary information on the left"
    access_token = access_token

    APP_ID = app_id
    API_KEY = api_key
    CLASSIFY_SECRET_KEY = classify_secret_key


    client = AipImageClassify(APP_ID, API_KEY, CLASSIFY_SECRET_KEY)
    # 定义可选参数
    options = {"baike_num": 5}
    # 调用图片标签识别接口
    result = client.advancedGeneral(image.file.read(), options)
    print("pic result:", result)
    keyword_list = []

    for res in result['result']:
        keyword_list.append(res['keyword'])
    keyword_string = ', '.join(keyword_list)
    content = '根据' + keyword_string + '写10首两句七言诗'
    erniebot.api_type = 'aistudio'
    erniebot.access_token = access_token
    response = erniebot.ChatCompletion.create(
        model='ernie-bot',
        messages=[{'role': 'user', 'content': f"{content}”"}],
    )

    data_str = response.result
    return data_str.replace("\n", "  ")

